package com.zk.iotgateway.bizhandler.impl;

import com.zk.iotgateway.bizhandler.AbstractIHandler;
import com.zk.iotgateway.bizhandler.IHandler;
import com.zk.iotgateway.domain.locator.LocatorDO;
import com.zk.iotgateway.manager.GlobalManager;
import com.zk.iotgateway.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author:mn.m
 * @create 2019-07-03 下午 04:30
 **/
@Component
@Scope("prototype")
public class CustomHandler extends AbstractIHandler{

    @Override
    public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        String o=(String) msg;
        byte[] dist= StringUtils.decodeHex(o);
        out.writeBytes(dist);
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        super.decode(ctx, in, out);
        System.out.println("is my impl hllll");
        int len = in.readableBytes();
        //数据包可读长度必须大于基本长度
        if (len >=6){
            byte[] dist=new byte[len];
            in.readBytes(dist);
            System.out.println("content in customcodec:"+ StringUtils.encodeHex(dist));
            out.add(StringUtils.encodeHex(dist));
        }
    }

    @Override
    public void handle(ChannelHandlerContext ctx, Object msg) throws Exception {

        String info = (String) msg;
        System.out.println("网关--customhandler "+ctx.channel().localAddress() + " 接收数据：" + info);
        this.dispatchMq(ctx, info);
        ctx.writeAndFlush("787801010D0A");
    }
}
